import styles from './index.module.scss'
import ArticleItem from '@/components/ArticleItem'
import { useEffect, useState } from 'react'
import { useDispatch, useSelector } from 'react-redux'
import { getArticleList, getMoreArticleList } from '@/store/actions/home'
import { PullToRefresh, InfiniteScroll } from 'antd-mobile-v5'
/**
 * 文章列表组件
 * @param {String} props.channelId 当前文章列表所对应的频道ID
 * @param {String} props.aid 当前 Tab 栏选中的频道ID
 */
const ArticleList = ({ channelId, aid }) => {
  const dispatch = useDispatch()
  // 获取数据
  const current = useSelector((state) => state.home.articles[channelId])
  // 是否有更多数据
  const [hasMore, setHasMore] = useState(true)
  // 代表是否正在加载数据
  const [loading, setLoading] = useState(false)

  useEffect(() => {
    // 如果该频道有文章数据，没必要一进来就发送请求
    if (current) return
    if (channelId === aid) {
      dispatch(getArticleList(channelId, Date.now()))
    }
  }, [channelId, aid, dispatch, current])

  //   console.log(current)
  // 不是当前id就不渲染
  if (!current) return null

  const onRefresh = async () => {
    setHasMore(true)
    await dispatch(getArticleList(channelId, Date.now()))
  }

  const loadMore = async () => {
    // 避免重复加载
    if (loading) return
    // 切换频道不加载
    if (channelId !== aid) return
    // 如果没数据
    if (!current.timestamp) {
      setLoading(false)
      return
    }

    setLoading(true)
    console.log('需要加载更多数据')
    try {
      await dispatch(getMoreArticleList(channelId, current.timestamp))
    } finally {
      setLoading(false)
    }
  }

  return (
    <div className={styles.root}>
      <PullToRefresh onRefresh={onRefresh}>
        <div className="articles">
          {current.list.map((item) => (
            <div className="article-item" key={item.art_id}>
              <ArticleItem
                channelId={channelId}
                articleList={item}
              ></ArticleItem>
            </div>
          ))}
        </div>
      </PullToRefresh>
      {/* 滚动刷新 */}
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
    </div>
  )
}

export default ArticleList
